<!-- 单页管理 -->
<template>
  <v-container>
    <v-data-table
      dense
      item-key="id"
      :headers="tableHeaders"
      :items="tableItems"
      :loading="tableLoading"
      must-sort
      calculate-widths
      :options.sync="tableOptions"
      :server-items-length="tableItemsTotal"
      :footer-props="{
        showFirstLastPage: true,
        showCurrentPage: true,
        itemsPerPageOptions: [5, 20, 30, 50]}">
      <template v-slot:top>
          <v-row dense no-gutters>
            <v-col cols="12">
              <v-btn text color="accent" @click="fetchData"><v-icon>refresh</v-icon>刷新</v-btn>
              <v-btn text color="primary" @click="btnAdd"><v-icon>add</v-icon>添加</v-btn>
              <v-divider></v-divider>
            </v-col>
          </v-row>
          <v-row>
            <v-col cols="12" sm="9">
              <v-form ref="searchField">
              <v-row no-gutters>
                <v-col cols="12" sm="5">
                  <v-select
                  :items="searchFieldItems"
                  prepend-icon="text_fields"
                  label="搜索字段"
                  dense
                  solo-inverted
                  flat
                  v-model="tableSearchField.field"/>
                </v-col>
                <v-col cols="12" sm="7">
                  <v-text-field
                  label="请输入搜索内容！"
                  prepend-icon="search"
                  dense
                  solo-inverted
                  flat
                  v-model="tableSearchField.keyword"/>
                </v-col>
              </v-row>
              </v-form>
            </v-col>
            <v-col cols="12" sm="3">
              <v-btn color="primary" @click="fetchData"><v-icon>search</v-icon>搜索</v-btn>
              <v-btn text @click="$refs.searchField.reset();fetchData()"><v-icon>refresh</v-icon>重置</v-btn>
            </v-col>
          </v-row>
      </template>
      <template v-slot:item.status="{ item }">
        <v-chip small color="green" dark>
          {{item.status}}
        </v-chip>
      </template>
      <template v-slot:item.action="{ item }">
        <v-btn icon small text color="black" disabled><v-icon>zoom_in</v-icon></v-btn>
        <v-btn icon small text color="info" @click.stop="btnEdit(item)"><v-icon small>edit</v-icon></v-btn>
        <v-btn icon small text color="red" @click.stop="deleteItemHandle([item])"><v-icon small>delete</v-icon></v-btn>
      </template>
    </v-data-table>
    <v-dialog persistent fullscreen :value="tableFormDialog" transition='scroll-x-transition'>
      <v-card>
        <v-app-bar color="primary" fixed>
          <v-btn icon dark @click="tableFormDialog = false">
            <v-icon>close</v-icon>
          </v-btn>
          <v-toolbar-title class="white--text">内容{{ mode === 'create' ? '新增' : '编辑' }}</v-toolbar-title>
          <v-spacer></v-spacer>
          <!-- <v-btn class="red" :disabled="formBtnDisabled" :loading="formBtnDisabled" @click="tableFormDialog = false"><v-icon>close</v-icon>取消</v-btn>
          <v-btn class="green" :disabled="formBtnDisabled" :loading="formBtnDisabled" @click="submit" color="secondary"><v-icon>check</v-icon>确定</v-btn> -->
          <v-btn dark text large class="warning" @click="deleteItemHandle([item])" :loading="formBtnDisabled" :disabled="formBtnDisabled"><v-icon>delete</v-icon>删除</v-btn>
          <v-btn dark text large class="red  mx-5" @click="submit('draft')" :loading="formBtnDisabled" :disabled="formBtnDisabled"><v-icon>drafts</v-icon>保存草稿</v-btn>
          <v-btn dark text large class="green" @click="submit('published')" :loading="formBtnDisabled" :disabled="formBtnDisabled"><v-icon>publish</v-icon>保存发布</v-btn>
        </v-app-bar>
        <v-card-text style="margin-top:50px;">
          <v-container>
            <v-form ref="dialogForm">
              <v-row>
                <v-col>
                  <v-text-field label="标题" v-model="tableFormData.title"></v-text-field>
                  <rich-text-editor :key="1" v-model="tableFormData.content"></rich-text-editor>
                  <v-text-field label="自定义链接" v-model="tableFormData.custom_path"></v-text-field>
                  <CommentSwitch v-model="tableFormData.comment" />
                  <image-upload v-model="tableFormData.images"></image-upload>
                </v-col>
              </v-row>
            </v-form>
          </v-container>
        </v-card-text>
      </v-card>
    </v-dialog>
  </v-container>
</template>
<script>
import * as API from '@/api/admin/pages.js'
import { ImageUpload, RichTextEditor } from '@/components/Form/'
import CommentSwitch from './components/CommentSwitch.vue'
export default {
  name: 'Pages',
  components: { ImageUpload, RichTextEditor, CommentSwitch },
  data: function () {
    return {
      tableHeaders: [
        // { text: 'ID', value: 'id' },
        { text: '标题', value: 'title', align: 'center' },
        { text: '自定义链接', value: 'custom_path', align: 'center' },
        { text: '评论', value: 'comment' },
        { text: '状态', value: 'status', width: 110, align: 'center' },
        { text: '发布时间', value: 'updatedAt', align: 'center' },
        { text: '操作', value: 'action', sortable: false, width: '118px', align: 'center' }
      ],
      tableLoading: false,
      tableItems: [],
      tableFormDialog: false,
      tableFormData: {},
      tableSelectItem: {},
      tableOptions: {
        page: 1,
        itemsPerPage: 20,
        sortBy: [ 'id' ],
        sortDesc: [ true ]
      }, // 分页参数
      tableItemsTotal: 0, // 总个数
      formBtnDisabled: false,
      tableSearchField: {
        field: '',
        keyword: ''
      },
      searchFieldItems: [
        { value: 'id', text: 'ID' },
        { value: 'title', text: '标题' },
        { value: 'custom_path', text: '自定义链接' }
      ]
    }
  },
  watch: {
    tableOptions: {
      handler () {
        this.fetchData()
      },
      deep: true
    }
  },
  computed: {
    mode: function() {
      return this.tableFormData.hasOwnProperty('id') ? 'edit' : 'create'
    }
  },
  methods: {
    fetchData: function() {
      this.tableLoading = true
      API.fetchList({
        sort: this.tableOptions.sortBy[0],
        descending: this.tableOptions.sortDesc[0],
        page: this.tableOptions.page,
        page_size: this.tableOptions.itemsPerPage,
        search: this.tableSearchField
      }).then(res => {
        this.tableItems = res.data.data
        this.tableItemsTotal = res.data.total
      }).catch(err => {
        this.$toasted.error(err.message)
      }).finally(() => {
        this.tableLoading = false
      })
    },
    btnAdd: function() {
      this.tableFormDialog = true
      this.tableFormData = {
        status: 'normal'
      }
    },
    btnEdit: function(item) {
      this.tableFormDialog = true
      this.tableFormData = item
    },
    submit: function(status) {
      this.$validator.validate().then(result => {
        if (result) {
          this.formBtnDisabled = true
          setTimeout(() => {
            this.formBtnDisabled = false // 点击一次时隔两秒后才能再次点击
          }, 2000)
          const submitFunc = this.mode === 'create' ? API.createOne : API.updateOne
          this.tableFormData.status = status
          submitFunc(this.tableFormData).then(res => {
            this.$toasted.success(res.data)
            this.tableFormDialog = false
            this.fetchData()
          }).catch(err => {
            return Promise.reject(err)
          }).finally(() => {
            this.formBtnDisabled = false
          })
        }
      })
    },
    deleteItemHandle: function(items) {
      if (confirm('是否确定删除？删除后无法恢复，请慎重！')) {
        API.deleteOne(items.map(e => e.id).join('_')).then(res => {
          // const index = this.tableItems.indexOf(item)
          // this.tableItems.splice(index, 1)
          this.fetchData()
          this.$toasted.success(res.data)
        }).catch(err => {
          return Promise.reject(err)
        })
      }
    }
  }
}
</script>
